<template>
  <div class="admin-container">
    <!-- 登录界面 -->
    <div v-if="!isAuthenticated" class="login-form">
      <h2>管理员登录</h2>
      <form @submit.prevent="login">
        <div class="form-group">
          <label for="password">密码：</label>
          <input
            type="password"
            id="password"
            v-model="password"
            required
            placeholder="请输入管理员密码"
          />
        </div>
        <div class="form-group">
          <label for="captcha">验证码：</label>
          <input
            type="text"
            id="captcha"
            v-model="captcha"
            required
            placeholder="请输入验证码"
          />
          <img
            :src="captchaImageUrl"
            alt="验证码"
            @click="refreshCaptcha"
            class="captcha-image"
          />
        </div>
        <button type="submit" class="login-button">登录</button>
      </form>
      <p v-if="loginError" class="error-message">{{ loginError }}</p>
    </div>

    <!-- 管理界面 -->
    <div v-else class="admin-section">
      <!-- 顶部选项卡 -->
      <div class="tabs">
        <button
          :class="['tab-button', { active: currentTab === 'videos' }]"
          @click="currentTab = 'videos'"
        >
          视频模型管理
        </button>
        <button
          :class="['tab-button', { active: currentTab === 'posts' }]"
          @click="currentTab = 'posts'"
        >
          待审核的帖子
        </button>
        <button
          :class="['tab-button', { active: currentTab === 'comments' }]"
          @click="currentTab = 'comments'"
        >
          待审核的评论
        </button>
      </div>

      <!-- 通知消息 -->
      <div v-if="message" :class="['message', messageType]">
        {{ message }}
      </div>

      <!-- 视频模型管理 -->
      <div v-if="currentTab === 'videos'" class="review-section">
        <h2>视频模型管理</h2>
        <div v-if="loadingVideos" class="loading-spinner"></div>
        <div v-else>
          <div v-if="userVideos.length === 0" class="no-videos">
            <p>没有用户上传的视频。</p>
          </div>
          <div class="videos-list">
            <div v-for="video in userVideos" :key="video.id" class="video-item">
              <p><strong>用户ID：</strong>{{ video.user_id }}</p>
              <p><strong>视频ID：</strong>{{ video.video_id }}</p>
              <p>
                <strong>上传时间：</strong>{{ formatDate(video.upload_time) }}
              </p>
              <video
                :src="video.video_url"
                controls
                class="video-preview"
              ></video>
              <div class="upload-model-section">
                <input
                  type="file"
                  @change="handleModelUpload($event, video)"
                  accept=".obj"
                />
                <button @click="uploadModel(video)" class="upload-model-button">
                  上传模型
                </button>
                <button @click="deleteVideo(video)" class="delete-video-button">
                  删除视频
                </button>
              </div>
            </div>
          </div>
        </div>
        <p v-if="errorMessage" class="error-message">{{ errorMessage }}</p>
      </div>

      <!-- 待审核的帖子 -->
      <div v-else-if="currentTab === 'posts'" class="review-section">
        <h2>待审核的帖子</h2>
        <div v-if="loadingPosts" class="loading-spinner"></div>
        <div v-else>
          <div v-if="pendingNews.length === 0" class="no-news">
            <p>没有待审核的帖子。</p>
          </div>
          <!-- 使用 transition-group 处理列表动画 -->
          <transition-group name="fade" tag="div" class="news-list">
            <div v-for="news in pendingNews" :key="news.id" class="news-item">
              <!-- 图片展示 -->
              <div v-if="news.image_url" class="news-image-container">
                <img :src="news.image_url" alt="新闻图片" class="news-image" />
              </div>

              <div class="news-details">
                <h3 class="news-title">{{ news.title }}</h3>
                <p><strong>ID：</strong>{{ news.id }}</p>
                <p><strong>作者：</strong>{{ news.author }}</p>
                <p><strong>日期：</strong>{{ formatDate(news.date) }}</p>
                <p><strong>内容：</strong>{{ news.summary }}</p>
                <p>
                  <strong>链接：</strong>
                  <a :href="news.link" target="_blank">{{ news.link }}</a>
                </p>
                <p><strong>点赞数：</strong>{{ news.likes }}</p>
                <div class="actions">
                  <button @click="approveNews(news.id)" class="approve-button">
                    审核通过
                  </button>
                  <button @click="rejectNews(news.id)" class="reject-button">
                    审核失败
                  </button>
                </div>
              </div>
            </div>
          </transition-group>
        </div>
        <p v-if="reviewErrorPosts" class="error-message">
          {{ reviewErrorPosts }}
        </p>
      </div>

      <!-- 待审核的评论 -->
      <div v-else-if="currentTab === 'comments'" class="review-section">
        <h2>待审核的评论</h2>
        <div v-if="loadingComments" class="loading-spinner"></div>
        <div v-else>
          <div v-if="pendingComments.length === 0" class="no-comments">
            <p>没有待审核的评论。</p>
          </div>
          <!-- 使用 transition-group 处理列表动画 -->
          <transition-group name="fade" tag="div" class="comments-list">
            <div
              v-for="comment in pendingComments"
              :key="comment.id"
              class="comment-item"
            >
              <p><strong>ID：</strong>{{ comment.id }}</p>
              <p><strong>新闻ID：</strong>{{ comment.news_id }}</p>
              <p><strong>用户：</strong>{{ comment.username }}</p>
              <p><strong>日期：</strong>{{ formatDate(comment.date) }}</p>
              <p><strong>评论内容：</strong>{{ comment.comment }}</p>
              <div class="actions">
                <button
                  @click="approveComment(comment.id)"
                  class="approve-button"
                >
                  审核通过
                </button>
                <button
                  @click="rejectComment(comment.id)"
                  class="reject-button"
                >
                  审核失败
                </button>
              </div>
            </div>
          </transition-group>
        </div>
        <p v-if="reviewErrorComments" class="error-message">
          {{ reviewErrorComments }}
        </p>
      </div>
    </div>
  </div>
</template>

<script>
import axios from "axios";
import { BASE_URL } from "@/config.js";

export default {
  name: "Admin",
  data() {
    return {
      password: "",
      captcha: "", // 用户输入的验证码
      captchaImageUrl: "", // 验证码图片的 URL
      isAuthenticated: false,
      loginError: "",
      // 视频模型管理
      userVideos: [],
      loadingVideos: false,
      errorMessage: "",
      modelFiles: {}, // 用于存储每个视频对应的模型文件
      // 其他数据...
      // 待审核的帖子
      pendingNews: [],
      loadingPosts: false,
      reviewErrorPosts: "",
      // 待审核的评论
      pendingComments: [],
      loadingComments: false,
      reviewErrorComments: "",
      // 当前选中的选项卡
      currentTab: "videos", // 'videos', 'posts' 或 'comments'
      // 通知消息
      message: "",
      messageType: "", // 'success' 或 'error'
    };
  },
  methods: {
    // 刷新验证码
    async refreshCaptcha() {
      try {
        const response = await axios.get(
          "https://www.lvjieshouji.cn:555/captcha",
          {
            responseType: "blob",
            withCredentials: true, // 确保携带cookie
          }
        );

        const url = URL.createObjectURL(response.data);
        this.captchaImageUrl = url;
      } catch (error) {
        console.error("刷新验证码失败:", error);
        this.captchaImageUrl = null;
      }
    },
    // 登录方法
    async login() {
      this.loginError = "";

      // 首先验证验证码
      try {
        const captchaResponse = await axios.get(
          "https://www.lvjieshouji.cn:555/verify_captcha",
          {
            params: {
              captcha: this.captcha.trim().toUpperCase(),
            },
            withCredentials: true,
          }
        );

        if (!captchaResponse.data.success) {
          this.loginError = "验证码错误，请重新输入。";
          this.refreshCaptcha(); // 刷新验证码
          return;
        }

        // 验证码正确，继续验证密码
        if (this.password === "shu_zhitong") {
          this.isAuthenticated = true;
          this.fetchUserVideos();
          this.fetchPendingNews();
          this.fetchPendingComments();
          this.showMessage("登录成功", "success");
        } else {
          this.loginError = "密码错误，请重新输入。";
          this.refreshCaptcha(); // 刷新验证码
        }
      } catch (error) {
        console.error("验证码验证失败:", error);
        this.loginError = "验证码验证失败，请稍后再试。";
        this.refreshCaptcha(); // 刷新验证码
      }
    },
    // 获取用户上传的视频...
    async fetchUserVideos() {
      this.loadingVideos = true;
      this.errorMessage = "";
      try {
        const response = await axios.get("/api/admin/user_videos");
        if (response.data.success) {
          this.userVideos = response.data.data;
        } else {
          this.errorMessage =
            response.data.error || "获取用户视频时出错，请稍后再试。";
        }
      } catch (error) {
        console.error("获取用户视频失败:", error);
        this.errorMessage = "获取用户视频时出错，请稍后再试。";
      } finally {
        this.loadingVideos = false;
      }
    },
    handleModelUpload(event, video) {
      const file = event.target.files[0];
      if (file) {
        if (!this.modelFiles) {
          this.modelFiles = {};
        }
        // Vue 3 中，直接赋值即可
        this.modelFiles[video.video_id] = file;
      }
    },
    async uploadModel(video) {
      const modelFile = this.modelFiles[video.video_id];
      if (!modelFile) {
        alert("请先选择模型文件");
        return;
      }
      const formData = new FormData();
      formData.append("model", modelFile);

      try {
        const response = await axios.post(
          `/api/admin/upload_model/${video.video_id}`,
          formData,
          {
            headers: { "Content-Type": "multipart/form-data" },
          }
        );
        if (response.data.success) {
          alert("模型上传成功");
          // 更新模型路径
          video.model_path = response.data.modelPath;
        } else {
          alert(response.data.error || "模型上传失败，请稍后再试。");
        }
      } catch (error) {
        console.error("模型上传失败:", error);
        alert("模型上传失败，请稍后再试。");
      }
    },

    // 删除视频
    async deleteVideo(video) {
      if (!confirm("确定要删除该视频吗？")) return;
      try {
        const response = await axios.post("/api/admin/delete_video", {
          videoId: video.video_id,
        });
        if (response.data.success) {
          // 从列表中移除视频
          this.userVideos = this.userVideos.filter(
            (v) => v.video_id !== video.video_id
          );
          // 显示消息
          this.showMessage("提供的视频存在问题，请重新上传", "success");
        } else {
          alert(response.data.error || "删除视频失败，请稍后再试。");
        }
      } catch (error) {
        console.error("删除视频失败:", error);
        alert("删除视频失败，请稍后再试。");
      }
    },
    // 获取待审核的帖子
    async fetchPendingNews() {
      this.loadingPosts = true;
      this.reviewErrorPosts = "";
      try {
        const response = await axios.get("/api/admin/news/pending");
        if (response.data.success) {
          this.pendingNews = response.data.data;
        } else {
          this.reviewErrorPosts =
            response.data.error || "获取待审核的帖子时出错，请稍后再试。";
        }
      } catch (error) {
        console.error("获取待审核帖子失败:", error);
        this.reviewErrorPosts = "获取待审核帖子时出错，请稍后再试。";
      } finally {
        this.loadingPosts = false;
      }
    },
    // 获取待审核的评论
    async fetchPendingComments() {
      this.loadingComments = true;
      this.reviewErrorComments = "";
      try {
        const response = await axios.get("/api/admin/comments/pending");
        if (response.data.success) {
          this.pendingComments = response.data.data;
        } else {
          this.reviewErrorComments =
            response.data.error || "获取待审核的评论时出错，请稍后再试。";
        }
      } catch (error) {
        console.error("获取待审核评论失败:", error);
        this.reviewErrorComments = "获取待审核评论时出错，请稍后再试。";
      } finally {
        this.loadingComments = false;
      }
    },
    // 审核通过帖子
    async approveNews(newsId) {
      if (!confirm("确定要审核通过这条帖子吗？")) return;
      try {
        const response = await axios.post(`/api/admin/news/${newsId}/approve`);
        if (response.data.success) {
          // 立即从数组中移除帖子，触发 transition-group 的离场动画
          this.pendingNews = this.pendingNews.filter(
            (news) => news.id !== newsId
          );
          // 显示成功消息
          this.showMessage("审核通过！", "success");
        } else {
          // 显示失败消息
          this.showMessage(
            response.data.error || "审核失败，请稍后再试。",
            "error"
          );
        }
      } catch (error) {
        console.error("审核通过失败:", error);
        this.showMessage("审核通过时出错，请稍后再试。", "error");
      }
    },
    // 审核失败帖子
    async rejectNews(newsId) {
      if (!confirm("确定要审核失败这条帖子吗？")) return;
      try {
        const response = await axios.post(`/api/admin/news/${newsId}/reject`);
        if (response.data.success) {
          // 立即从数组中移除帖子，触发 transition-group 的离场动画
          this.pendingNews = this.pendingNews.filter(
            (news) => news.id !== newsId
          );
          // 显示成功消息
          this.showMessage("审核失败！", "success");
        } else {
          // 显示失败消息
          this.showMessage(
            response.data.error || "审核失败，请稍后再试。",
            "error"
          );
        }
      } catch (error) {
        console.error("审核失败失败:", error);
        this.showMessage("审核失败时出错，请稍后再试。", "error");
      }
    },
    // 审核通过评论
    async approveComment(commentId) {
      if (!confirm("确定要审核通过这条评论吗？")) return;
      try {
        const response = await axios.post(
          `/api/admin/comments/${commentId}/approve`
        );
        if (response.data.success) {
          // 立即从数组中移除评论，触发 transition-group 的离场动画
          this.pendingComments = this.pendingComments.filter(
            (comment) => comment.id !== commentId
          );
          // 显示成功消息
          this.showMessage("评论审核通过！", "success");
        } else {
          // 显示失败消息
          this.showMessage(
            response.data.error || "评论审核失败，请稍后再试。",
            "error"
          );
        }
      } catch (error) {
        console.error("评论审核通过失败:", error);
        this.showMessage("评论审核通过时出错，请稍后再试。", "error");
      }
    },
    // 审核失败评论
    async rejectComment(commentId) {
      if (!confirm("确定要审核失败这条评论吗？")) return;
      try {
        const response = await axios.post(
          `/api/admin/comments/${commentId}/reject`
        );
        if (response.data.success) {
          // 立即从数组中移除评论，触发 transition-group 的离场动画
          this.pendingComments = this.pendingComments.filter(
            (comment) => comment.id !== commentId
          );
          // 显示成功消息
          this.showMessage("评论审核失败！", "success");
        } else {
          // 显示失败消息
          this.showMessage(
            response.data.error || "评论审核失败，请稍后再试。",
            "error"
          );
        }
      } catch (error) {
        console.error("评论审核失败失败:", error);
        this.showMessage("评论审核失败时出错，请稍后再试。", "error");
      }
    },
    // 格式化日期
    formatDate(dateString) {
      const options = {
        year: "numeric",
        month: "2-digit",
        day: "2-digit",
        hour: "2-digit",
        minute: "2-digit",
      };
      return new Date(dateString).toLocaleDateString("zh-CN", options);
    },
    // 显示通知消息
    showMessage(msg, type) {
      this.message = msg;
      this.messageType = type;
      // 自动隐藏消息
      setTimeout(() => {
        this.message = "";
        this.messageType = "";
      }, 3000); // 3秒后自动隐藏
    },
  },
  mounted() {
    this.refreshCaptcha(); // 初始加载验证码图片
  },
};
</script>

<style scoped>
@import url('https://fonts.googleapis.com/css2?family=Montserrat:wght@400;700&family=Playfair+Display&display=swap');

/* 通用背景 & 主容器 */
.admin-container {
  position: relative;
  min-height: 100vh;
  margin: 0;
  padding: 0;
  font-family: 'Montserrat', sans-serif;
  color: #fdf6e3;
  background: #1c2827 url('@/assets/s2.jpg') no-repeat center/cover fixed;
  display: flex;
  align-items: center;
  justify-content: center;
}
.admin-container::before {
  content: '';
  position: absolute;
  inset: 0;
  background-color: rgba(0, 0, 0, 0.6);
  z-index: 0;
}

/* 登录表单 */
.login-form {
  position: relative;
  z-index: 1;
  width: 100%;
  max-width: 480px;
  padding: 30px;
  background: rgba(30, 30, 30, 0.95);
  border-radius: 20px;
  box-shadow: 0 8px 20px rgba(0,0,0,0.7);
  text-align: center;
}
.login-form h2 {
  font-family: 'Playfair Display', serif;
  font-size: 28px;
  color: #d4af37;
  margin-bottom: 20px;
  text-shadow: 1px 1px 3px rgba(0,0,0,0.5);
}
.form-group {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}
.form-group label {
  width: 100px;
  color: #d4af37;
  text-align: right;
  margin-right: 10px;
  font-size: 16px;
}
.form-group input {
  flex: 1;
  padding: 10px;
  border-radius: 10px;
  border: 1px solid #555;
  background: #2e2e2e;
  color: #fdf6e3;
  font-size: 16px;
  transition: border-color 0.3s;
}
.form-group input:focus {
  outline: none;
  border-color: #d4af37;
}
.captcha-image {
  margin-left: 10px;
  height: 40px;
  border-radius: 10px;
  cursor: pointer;
  transition: opacity 0.3s;
}
.captcha-image:hover {
  opacity: 0.8;
}
.login-button {
  margin-top: 20px;
  padding: 10px 25px;
  min-width: 140px;
  font-size: 17px;
  font-weight: 700;
  color: #2e2e2e;
  background: #d4af37;
  border: none;
  border-radius: 30px;
  cursor: pointer;
  box-shadow: 0 6px 15px rgba(0,0,0,0.5);
  transition: transform 0.3s, box-shadow 0.3s;
}
.login-button:hover {
  transform: translateY(-3px);
  box-shadow: 0 8px 20px rgba(0,0,0,0.6);
}
.error-message {
  margin-top: 15px;
  padding: 10px;
  background: rgba(231,76,60,0.2);
  color: #e74c3c;
  border-radius: 10px;
  border: 1px solid rgba(231,76,60,0.4);
  font-weight: 500;
}

/* 管理界面整体 & 下移内容 */
.admin-section {
  position: relative;
  z-index: 1;
  width: 100%;
  max-width: 1200px;
  padding: 80px 40px 40px; /* 顶部内边距加大，让内容下移 */
  background: rgba(28,40,39,0.9);
  border-radius: 20px;
  box-shadow: 0 8px 20px rgba(0,0,0,0.7);
}

/* 顶部选项卡 */
.tabs {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-bottom: 30px;
}
.tab-button {
  font-family: 'Playfair Display', serif;
  font-size: 20px;
  font-weight: 700;
  padding: 10px 25px;
  border-radius: 30px;
  border: 2px solid #5e4b3c;
  background: linear-gradient(135deg, #1c2827, #5e4b3c);
  color: #d4af37;
  cursor: pointer;
  text-shadow: 1px 1px 2px rgba(0,0,0,0.5);
  transition: all 0.3s ease;
}
.tab-button:hover {
  transform: translateY(-3px);
  box-shadow: 0 6px 15px rgba(0,0,0,0.7);
}
.tab-button.active {
  background: linear-gradient(135deg, #5e4b3c, #8b4513);
  border-color: #d4af37;
  color: #fdf6e3;
}

/* 通知消息 */
.message {
  position: fixed;
  top: 20px;
  right: 20px;
  padding: 15px 30px;
  border-radius: 20px;
  font-size: 16px;
  box-shadow: 0 4px 12px rgba(0,0,0,0.5);
  z-index: 1000;
}
.message.success { background-color: #5e4b3c; color: #fdf6e3; }
.message.error   { background-color: #8b4513; color: #fdf6e3; }

/* 审核区通用 */
.review-section {
  margin-top: 20px;
  background: rgba(46,46,46,0.9);
  border-radius: 20px;
  padding: 30px;
  box-shadow: inset 0 0 10px rgba(0,0,0,0.7);
}
.review-section h2 {
  font-family: 'Playfair Display', serif;
  font-size: 28px;
  color: #d4af37;
  text-align: center;
  margin-bottom: 20px;
  text-shadow: 1px 1px 2px rgba(0,0,0,0.5);
}

/* 视频与评论列表网格 */
.videos-list,
.comments-list {
  display: grid;
  grid-template-columns: 1fr;
  gap: 25px;
}
@media (min-width: 800px) {
  .videos-list,
  .comments-list {
    grid-template-columns: 1fr 1fr;
  }
}

/* 卡片样式 */
.video-item,
.comment-item {
  background: #2e2e2e;
  border: 2px solid #5e4b3c;
  border-radius: 20px;
  padding: 20px;
  box-shadow: 0 6px 18px rgba(0,0,0,0.7);
  transition: transform 0.3s, box-shadow 0.3s;
}
.video-item:hover,
.comment-item:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 25px rgba(0,0,0,0.8);
}

/* 文本内容 */
.video-item p,
.comment-item p {
  color: #e0d8c3;
  font-size: 15px;
  margin: 6px 0;
}

/* 视频预览 */
.video-preview {
  display: block;
  width: 100%;
  max-height: 300px;
  border-radius: 12px;
  margin: 15px 0;
  box-shadow: inset 0 0 8px rgba(0,0,0,0.7);
}

/* 文件选择按钮美化 */
.upload-model-section input[type="file"] {
  font-family: 'Montserrat', sans-serif;
  cursor: pointer;
}
.upload-model-section input[type="file"]::file-selector-button {
  padding: 8px 16px;
  margin-right: 10px;
  border: 2px solid #d4af37;
  border-radius: 20px;
  background-color: #5e4b3c;
  color: #fdf6e3;
  font-weight: 600;
  transition: background-color 0.3s, transform 0.3s;
}
.upload-model-section input[type="file"]::file-selector-button:hover {
  background-color: #8b4513;
  transform: translateY(-2px);
}

/* 操作区按钮 */
.upload-model-button,
.delete-video-button,
.approve-button,
.reject-button {
  font-family: 'Montserrat', sans-serif;
  font-weight: 600;
  padding: 10px 20px;
  margin-top: 10px;
  margin-right: 10px;
  border-radius: 25px;
  border: none;
  cursor: pointer;
  box-shadow: 0 4px 10px rgba(0,0,0,0.6);
  transition: all 0.3s ease;
}
.upload-model-button { background: #d4af37; color: #2e2e2e; }
.upload-model-button:hover { background: #b89c34; }
.delete-video-button,
.reject-button { background: #8b4513; color: #fdf6e3; }
.delete-video-button:hover,
.reject-button:hover { background: #5e4b3c; }
.approve-button { background: #5e4b3c; color: #fdf6e3; }
.approve-button:hover { background: #8b4513; }

/* ——— “待审核的帖子” 部分专属样式 ——— */
.news-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
  margin: 0;
  padding: 0;
  list-style: none;
}
.news-item {
  display: flex;
  flex-direction: column;
  background: #2e2e2e;
  border: 2px solid #5e4b3c;
  border-radius: 16px;
  padding: 16px;
  box-shadow: 0 4px 12px rgba(0,0,0,0.6);
  overflow: hidden;
}
@media (min-width: 768px) {
  .news-item {
    flex-direction: row;
    align-items: flex-start;
  }
}
.news-image-container {
  flex: 0 0 160px;
  max-width: 160px;
  max-height: 120px;
  margin-bottom: 12px;
  overflow: hidden;
  border-radius: 12px;
}
@media (min-width: 768px) {
  .news-image-container {
    margin-bottom: 0;
    margin-right: 20px;
  }
}
.news-image {
  display: block;
  width: 100%;
  height: 100%;
  object-fit: cover;
}
.news-details {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 6px;
  color: #e0d8c3;
  overflow: hidden;
}
.news-title {
  font-size: 18px;
  font-weight: 700;
  color: #d4af37;
  margin: 0 0 8px 0;
  line-height: 1.2;
  text-shadow: 1px 1px 2px rgba(0,0,0,0.5);
}
.news-details p {
  margin: 0;
  font-size: 14px;
  line-height: 1.4;
  overflow: hidden;
  text-overflow: ellipsis;
}
.news-details a {
  color: #b89c34;
  word-break: break-all;
  text-decoration: none;
}
.news-details a:hover {
  text-decoration: underline;
}

/* 无数据提示 */
.no-videos,
.no-news,
.no-comments {
  background: #3e2a1f;
  color: #d4af37;
  padding: 40px;
  border-radius: 20px;
  text-align: center;
  font-size: 18px;
  box-shadow: inset 0 0 10px rgba(0,0,0,0.7);
}
</style>
